<?php


class Application_Model_Dao_StockMapper extends Base_Mapper
{
	function __construct() {
		parent::__construct();
		$this->tableName = 'Application_Model_DbTable_Stock';
	}

	public function save(Application_Model_BusiInfo_Stock $model)
	{
		
		$data = array(
			"id" => $model->__get("id"),
			"stockin_id" => $model->__get("stockinId"),
			'steel_id' => $model->__get("steelId"),
			'specs' => $model->__get("specs"),
			'length' => $model->__get("length"),
			'cost_price' => $model->__get("costPrice"),
			'amount' => $model->__get("amount"),
			'weight' => $model->__get("weight"),
		);
		$this->logger->log(print_r($data,true),Zend_log::DEBUG);
		
		$id = $model->__get("id"); 
		
		if ($id == null || $id == "") {
			unset($data['id']);
			if($data['specs'] != "dummy") {
				$record_id = $this->getDbTable()->insert($data);
			}
		} elseif($data['specs'] != "dummy"){
			$this->getDbTable()->update($data, array('id = ?' => $id));
		} else {
			$this->delete($id);
		}
	}
   
	public function find($id)
	{
		$result = $this->getDbTable()->find($id);
		if (0 == count($result)) {
			return;
		}
		$row = $result->current();
		return $this->toModel($row);		
	}
   
	public function fetchAll($stockinId = null)
	{
		if ($stockinId == null) {
			$resultSet = $this->getDbTable()->fetchAll();
		} else {
			$resultSet = $this->getDbTable()->fetchAll("stockin_id = ".$stockinId);
		}
		$entries   = array();
		foreach ($resultSet as $row) {	
			$entry = $this->toModel($row);
			$entries[] = $entry;
		}
		return $entries;
	}
	
	private function toModel($record){
		return new Application_Model_BusiInfo_Stock(array(
			"id" => $record["id"],
			"stockinId" => $record["stockin_id"],
			"steelId" => $record["steel_id"],
			"specs" => $record["specs"],
			"length" => $record["length"],
			"costPrice" => $record["cost_price"],
			"amount" => $record["amount"],
			"weight" => $record["weight"],
		)); 
		
	}
	
	public function delete($id) {		
		$this->getDbTable()->delete( "id=" . $id);
	}
	public function deleteByStockinId($id) {		
		$this->getDbTable()->delete( "stockin_id=" . $id);
	}
}

